import {ElForm} from 'element-ui/types/form';
import {BindingResultObject, Params, Result} from '*.vue';

const baseURL = process.env.VUE_APP_BASE_API;

// 表单重置
export function resetForm(this: any, refName: string): void {
    if (this.$refs[refName] !== undefined) {
        this.$refs[refName].resetFields();
    }
}

export function isMobile() {
    return navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i);
}

// 通用下载方法
// export function download(fileName: string): void {
//  let url=   baseURL + "/resources/download?fileName=" + encodeURI(fileName);
//     window.open(url,'_blank')
// }
// 通用下载方法
export function download(fileName) {
    window.location.href = baseURL + '/resources/download?fileName=' + encodeURI(fileName) + '&_=' + new Date().getTime();
}


export const mimeMap = {
    xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    zip: 'application/zip',
};

/**
 * 解析blob响应内容并下载
 * @param {*} res blob响应内容
 * @param {String} mimeType MIME类型
 */
export function resolveBlob(res, mimeType) {
    const aLink = document.createElement('a');
    const blob = new Blob([res.data], {type: mimeType});
    // //从response的headers中获取filename, 后端response.setHeader("Content-disposition", "attachment; filename=xxxx.docx") 设置的文件名;
    const patt = new RegExp('filename=([^;]+\\.[^.;]+);*');
    const contentDisposition = decodeURI(res.headers['content-disposition']);
    const result = patt.exec(contentDisposition);
    if (result) {
        let fileName = result[1];
        fileName = fileName.replace(/"/g, '');
        aLink.href = URL.createObjectURL(blob);
        aLink.setAttribute('download', fileName); // 设置下载文件名称
        document.body.appendChild(aLink);
        aLink.click();
        document.body.removeChild(aLink) // 释放标签
    }
}


/**
 * 过滤对象参数为空或者null的属性
 * 这个方法不会影响原来的对象，而是返回一个新对象
 * @param obj
 */
export function filterParams(obj: Params) {
    const _newPar = {};
    for (const key in obj) {
        //如果对象属性的值不为空，就保存该属性（这里我做了限制，如果属性的值为0，保存该属性。如果属性的值全部是空格，属于为空。）
        if (Object.hasOwnProperty.call(obj, key) && (obj[key] === 0 || obj[key] === false || obj[key]) && obj[key].toString().replace(/(^\s*)|(\s*$)/g, '') !== '') {
            _newPar[key] = obj[key];
        }
    }
    return _newPar;
}

/**
 * 回显后端表单校验错误结果
 * @param result 后端错误信息
 * @param form 表单对象
 * @param rule 校验函数
 */
export function validateForm(result: Result, form: ElForm, rule: any) {
    if (result.code === 400) {
        const errMessage: BindingResultObject[] = result.data;
        if (errMessage && errMessage.length > 0) {
            const rules = JSON.parse(JSON.stringify(rule));
            const props: string[] = [];
            errMessage.forEach((item, index) => {
                props.push(item.field);
                rule[item.field].push({
                    // js新增一个自定义校验
                    validator: (rule, value, callback) => {
                        callback(new Error(item.message ? item.message : '未知错误'))
                    },
                    trigger: 'blur'
                });
            });
            form.validateField(props, function (errorMessage: string) {
                console.log(errorMessage)
            }); // 手动校验

            errMessage.forEach((item, index) => {
                rule[item.field] = rules[item.field];
            })
        }
    }
}

export function changeMem(limit: any) {
    let size = "";
    if (limit < 0.1 * 1024) {                            //小于0.1KB，则转化成B
        size = limit.toFixed(2) + "B"
    } else if (limit < 0.1 * 1024 * 1024) {            //小于0.1MB，则转化成KB
        size = (limit / 1024).toFixed(2) + "KB"
    } else if (limit < 0.1 * 1024 * 1024 * 1024) {        //小于0.1GB，则转化成MB
        size = (limit / (1024 * 1024)).toFixed(2) + "MB"
    } else {                                            //其他转化成GB
        size = (limit / (1024 * 1024 * 1024)).toFixed(2) + "GB"
    }

    const sizeStr = size + "";                        //转成字符串
    const index = sizeStr.indexOf(".");                    //获取小数点处的索引
    const dou = sizeStr.substr(index + 1, 2)            //获取小数点后两位的值
    if (dou == "00") {                                //判断后两位是否为00，如果是则删除00
        return sizeStr.substring(0, index) + sizeStr.substr(index + 3, 2)
    }
    return size;
}

/**
 * 格式化秒
 * @param value 总秒数
 * @return string result 格式化后的字符串
 */
export function formatSeconds(value: string) {
    let theTime = parseInt(value);// 需要转换的时间秒
    let theTime1 = 0;// 分
    let theTime2 = 0;// 小时
    let theTime3 = 0;// 天
    if (theTime > 60) {
        theTime1 = parseInt(String(theTime / 60));
        theTime = parseInt(String(theTime % 60));
        if (theTime1 > 60) {
            theTime2 = parseInt(String(theTime1 / 60));
            theTime1 = parseInt(String(theTime1 % 60));
            if (theTime2 > 24) {
                //大于24小时
                theTime3 = parseInt(String(theTime2 / 24));
                theTime2 = parseInt(String(theTime2 % 24));
            }
        }
    }
    let result = '';
    if (theTime > 0) {
        result = "" + parseInt(String(theTime)) + "秒";
    }
    if (theTime1 > 0) {
        result = "" + parseInt(String(theTime1)) + "分" + result;
    }
    if (theTime2 > 0) {
        result = "" + parseInt(String(theTime2)) + "小时" + result;
    }
    if (theTime3 > 0) {
        result = "" + parseInt(String(theTime3)) + "天" + result;
    }
    return result;
}
